<?php
include_once LIBRARY_DIRECTORY . 'Model.php';

class StopwordManagement extends Model {
	
	private $_stopword = array();
	private $_existingStopWord = array();
	
	/**
	 * construct
	 *
	 * @param array $stopword
	 */
	public function __construct($stopword = array())
	{
		// input this array of stop words
		foreach ($stopword as &$stopwordItem)
		{
			$stopwordItem = trim($stopwordItem);
		}
		$this->_stopword = $stopword;
		
		// get the array of existing stop words from db
		$this->_existingStopWord = $this->getAllStopword();
	}
	
	/**
	 * get all existing stopwords from db
	 * 
	 * @return array
	 *
	 */
	public function getAllStopword()
	{
		$tblName = TBL_STOPWORD;
		$q = "SELECT * FROM $tblName";
		$records = $this->fetchMultiple($q);
		
		$stopword = array();
		foreach ($records as $item)
		{
			$stopword[] = $item['stopword_word'];
		}
		
		return $stopword;
	}
	
	/**
	 * save this array of stopword in to database
	 *
	 * @return 0|1
	 */
	public function saveStopword()
	{
		$stopword = $this->_stopword;
		$existingStopWords = $this->_existingStopWord;
		
		if (!empty($stopword))
		{
			// select table name
			$tblName = TBL_STOPWORD;
			// array to store saved stop words
			$arrayStopwordToSave = array();
			foreach ($stopword as $stopwordItem)
				if (!empty($stopwordItem) && !in_array($stopwordItem, $existingStopWords) && !in_array($stopwordItem, $arrayStopwordToSave))
				{
					$arrayStopwordToSave[] = $stopwordItem;
				}
			// create query to insert records into db
			if (!empty($arrayStopwordToSave))
			{
				$values = '';
				for ($i=0; $i<count($arrayStopwordToSave); $i++)
				{
					$word = $arrayStopwordToSave[$i];
					$values .= "('$word')";
					if ($i < count($arrayStopwordToSave)-1)
						$values .= ', ';
				}
				$q = "INSERT INTO $tblName(stopword_word) VALUES $values";
				$this->insert($q);
				
				return 1;
			}
		}
		
		return 0;
	}

}